package com.ipan.jfinal.render;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;

import com.ipan.jfinal.controller.ResultDefineManager;
import com.ipan.kits.base.type.Pair;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderManager;

/**
 * 自定义异常渲染 根据前端请求的是HTML、Json来做不同的渲染；
 * 
 * @author iPan
 * @version 2018-05-06
 */
public class MyErrorOldRender extends Render {

	protected static final String htmlContentType = "text/html; charset=" + getEncoding();
	protected static final String jsonContentType = "application/json; charset=" + getEncoding();

//	protected static final String version = "<center><a href='http://www.jfinal.com?f=ev-" + Const.JFINAL_VERSION
//			+ "' target='_blank'><b>Powered by JFinal " + Const.JFINAL_VERSION + "</b></a></center>";

	protected static final String version = "";
	
	protected static final String html404 = "<html><head><title>404 Not Found</title></head><body bgcolor='white'><center><h1>404 Not Found</h1></center><hr>"
			+ version + "</body></html>";
	protected static final String html500 = "<html><head><title>500 Internal Server Error</title></head><body bgcolor='white'><center><h1>500 Internal Server Error</h1></center><hr>"
			+ version + "</body></html>";
	protected static final String html401 = "<html><head><title>401 Unauthorized</title></head><body bgcolor='white'><center><h1>401 Unauthorized</h1></center><hr>"
			+ version + "</body></html>";
	protected static final String html403 = "<html><head><title>403 Forbidden</title></head><body bgcolor='white'><center><h1>403 Forbidden</h1></center><hr>"
			+ version + "</body></html>";
	
	protected static final String json404 = "{\"code\": 404, \"msg\": \"404 请求失败\"}";
	protected static final String json500 = "{\"code\": 500, \"msg\": \"500 操作失败\"}";
	protected static final String json401 = "{\"code\": 401, \"msg\": \"401 认证失败\"}";
	protected static final String json403 = "{\"code\": 403, \"msg\": \"403 权限不足\"}";

	protected int errorCode;

	public MyErrorOldRender(int errorCode, String view) {
		this.errorCode = errorCode;
		this.view = view;
	}

	public void render() {
		// render with html content
		PrintWriter writer = null;
		try {
			String wrBody = null;
			if (isAjax(request)) { // ajax请求，这里是json请求；如果是XML，自己定义！
				wrBody = getErrorJson();
				response.setStatus(200); // ajax请求响应必须是200才能正常接收
				response.setContentType(jsonContentType);
			} else {
				wrBody = getErrorHtml(); // 生成错误页面 并且 当自定义了错误页面时候，设置errorMsg的提示！
				
				// render with view
				String view = getView();
				if (view != null) {
					response.setStatus(getErrorCode()); // HttpServletResponse.SC_XXX_XXX
					RenderManager.me().getRenderFactory().getRender(view).setContext(request, response).render();
					return;
				}
				
				response.setStatus(getErrorCode()); // HttpServletResponse.SC_XXX_XXX
				response.setContentType(htmlContentType);
			}
			writer = response.getWriter();
			writer.write(wrBody);
			writer.flush();
		} catch (IOException e) {
			throw new RenderException(e);
		}
	}

	public String getErrorHtml() {
		int errorCode = getErrorCode();
		if (errorCode == 404) {
			request.setAttribute("errorMsg", "找不到页面！");
			return html404;
		}
		if (errorCode == 500) {
			request.setAttribute("errorMsg", "系统出错！");
			return html500;
		}
		if (errorCode == 401) {
			request.setAttribute("errorMsg", "认证失败！");
			return html401;
		}
		if (errorCode == 403) {
			request.setAttribute("errorMsg", "权限不足！");
			return html403;
		}
		Pair<String, String> pair = ResultDefineManager.me().get(errorCode + "");
		String msg = (pair != null) ? pair.getRight() : "";
		return "<html><head><title>" + errorCode + " Error</title></head><body bgcolor='white'><center><h1>" + errorCode
				+ " " + msg + "</h1></center><hr>" + version + "</body></html>";
	}
	
	public String getErrorJson() {
		int errorCode = getErrorCode();
		if (errorCode == 404)
			return json404;
		if (errorCode == 500)
			return json500;
		if (errorCode == 401)
			return json401;
		if (errorCode == 403)
			return json403;
		return String.format("{code: %d, msg: '%d操作失败'}", errorCode, errorCode);
	}

	public int getErrorCode() {
		return (errorCode != 0) ? errorCode : 100; // 对应BaseController中的retFail方法，失败返回code=100；
	}
	
	public boolean isAjax(HttpServletRequest request) {
		return ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) ? true : false;
	}
}
